/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.member.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.member.entity.MemberBonus;
import com.jeeplus.modules.member.entity.MemberSubs;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.sys.service.SystemService;

/**
 * 用户信息Controller
 * @author freedom
 * @version 2020-08-23
 */
@Controller
@RequestMapping(value = "${adminPath}/member/member")
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;
	@Autowired
	private AccountService accountService;
	
	@ModelAttribute
	public Member get(@RequestParam(required=false) String id) {
		Member entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = memberService.get(id);
			if (StringUtils.isNotBlank(entity.getRegionPlace())){
				String city = entity.getRegionPlace()
						.replaceAll("省","省/").replaceAll("市","市/");
				entity.setRegionPlace(city);
			}
		}
		if (entity == null){
			entity = new Member();
		}
		return entity;
	}
	
	/**
	 * 用户信息列表页面
	 */
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = {"list", ""})
	public String list(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/member/memberList";
	}


	/**
	 * 用户实名认证信息列表页面
	 */
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = {"confirmList"})
	public String confirmList(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/member/memberConfirmList";
	}
	
		/**
	 * 用户信息列表数据
	 */
	@ResponseBody
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Member> page = memberService.findPage(new Page<Member>(request, response), member); 
		return getBootstrapData(page);
	}

	/**
	 * 用户信息列表数据
	 */
	@ResponseBody
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = "participatingUsers")
	public Map<String, Object> participatingUsers(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		String orderNo = request.getParameter("orderNo");
		Page<Member> page = memberService.findMembers(new Page<Member>(request,response), orderNo, member);
		return getBootstrapData(page);
	}


	/**
	 * 查看，增加，编辑用户信息表单页面
	 */
	@RequiresPermissions(value={"member:member:view","member:member:add","member:member:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, Member member, Model model) {
		model.addAttribute("member", member);
		model.addAttribute("mode", mode);
		return "modules/member/memberForm";
	}

	/**
	 * 保存用户信息
	 */
	@ResponseBody
	@RequiresPermissions(value={"member:member:add","member:member:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Member member, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(member);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		if (StringUtils.isNotBlank(member.getRegionPlace())){
			String city = member.getRegionPlace()
					.replaceAll("省/","省").replaceAll("市/","市");
			member.setRegionPlace(city);
		}
		if (!member.getIsNewRecord()){
			if (!memberService.get(member.getId()).getUsertype().equals(member.getUsertype())){
				member.setRemarks("6");
			}
		}

		//新增或编辑表单保存
		if(StringUtils.isEmpty(member.getId())) {
			memberService.saveNew(member);
		}else {
			if(StringUtils.isNotEmpty(member.getPwd())) {
				member.setPassword(SystemService.entryptPassword(member.getPwd()));
//				member.setPassword(member.getPwd());
			}
			if(StringUtils.isNotEmpty(member.getJypwd())) {
				member.setTranspwd(SystemService.entryptPassword(member.getJypwd()));
			}
			memberService.save(member);
		}
		j.setSuccess(true);
		j.setMsg("保存用户信息成功");
		return j;
	}
	
	/**
	 * 删除用户信息
	 */
	@ResponseBody
	@RequiresPermissions("member:member:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Member member) {
		AjaxJson j = new AjaxJson();
		memberService.delete(member);
		j.setMsg("删除用户信息成功");
		return j;
	}
	
	/**
	 * 批量删除用户信息
	 */
	@ResponseBody
	@RequiresPermissions("member:member:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			Member member = memberService.get(id);
//			if (member.getP() != null){
//				Member upMem = get(member.getP().getId());
//				if (upMem != null && upMem.getNum() > 0){
//					upMem.setNum(upMem.getNum() - 1);
//					memberService.save(upMem);
//				}
//				while (upMem != null){
//					Account account = accountService.get(upMem.getAccount().getId());
//					if (account.getNum() > 0){
//						account.setNum(account.getNum() - 1);
//						accountService.save(account);
//					}
//					if (upMem.getP() != null){
//						upMem = get(upMem.getP().getId());
//					}else {
//						break;
//					}
//				}
//			}
			memberService.delete(member);
		}
		j.setMsg("删除用户信息成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("member:member:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Member member, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "用户信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Member> page = memberService.findPage(new Page<Member>(request, response, -1), member);
    		new ExportExcel("用户信息", Member.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出用户信息记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("member:member:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Member> list = ei.getDataList(Member.class);
			for (Member member : list){
				try{
					memberService.save(member);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户信息记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条用户信息记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入用户信息失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入用户信息数据模板
	 */
	@ResponseBody
	@RequiresPermissions("member:member:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "用户信息数据导入模板.xlsx";
    		List<Member> list = Lists.newArrayList(); 
    		new ExportExcel("用户信息数据", Member.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


	/**
	 * 批量通过用户实名认证信息
	 */
	@ResponseBody
	@RequestMapping(value = "confirmMembers")
	public AjaxJson confirmMembers(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			memberService.confirmIdCode(memberService.get(id));
		}
		j.setMsg("审核用户实名认证信息成功");
		return j;
	}


	/**
	 * 批量驳回用户实名认证信息
	 */
	@ResponseBody
	@RequestMapping(value = "rejectMembers")
	public AjaxJson rejectMembers(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			memberService.rejectIdCode(memberService.get(id));
		}
		j.setMsg("审核用户实名认证信息成功");
		return j;
	}


	/**
	 * 用户分红数字列表页面
	 */
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = {"bonusList"})
	public String bonusList(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/member/bonusList";
	}

	/**
	 * 用户分红数字列表数据
	 */
	@ResponseBody
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = "bonusListData")
	public Map<String, Object> bonusListData(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Member> page = memberService.findBonusPage(new Page<Member>(request, response), member);
		return getBootstrapData(page);
	}



	/**
	 * 各团队认购统计列表页面
	 */
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = {"inviteInfoList"})
	public String inviteInfoList(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/member/inviteInfoList";
	}

	/**
	 * 各团队认购统计列表页面
	 */
	@ResponseBody
	@RequiresPermissions("member:member:list")
	@RequestMapping(value = "teamData")
	public Map<String, Object> teamData(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Member> page = memberService.findTeamPage(new Page<Member>(request, response), member);
		return getBootstrapData(page);
	}


	/**
	 * 导出分红数字excel文件
	 */
	@ResponseBody
	@RequiresPermissions("member:member:export")
	@RequestMapping(value = "exportBonus")
	public AjaxJson exportBonus(Member member, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "用户分红信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Member> page = memberService.findBonusPage(new Page<Member>(request, response, -1), member);
			List<MemberBonus> list = new ArrayList<>();
			List<Member> memberList = page.getList();
			if (memberList.size() > 0){
				for (Member member1 : memberList) {
					MemberBonus memberBonus = new MemberBonus();
					memberBonus.setLoginName(member1.getLoginName());
					memberBonus.setBonus(member1.getBonus());
					list.add(memberBonus);
				}
			}
			new ExportExcel("用户分红信息", MemberBonus.class).setDataList(list).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出用户分红信息记录失败！失败信息："+e.getMessage());
		}
		return j;
	}


	/**
	 * 导出团队认购excel文件
	 */
	@ResponseBody
	@RequiresPermissions("member:member:export")
	@RequestMapping(value = "exportSubs")
	public AjaxJson exportSubs(Member member, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "团队认购信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Member> page = memberService.findTeamPage(new Page<Member>(request, response, -1), member);
			List<MemberSubs> list = new ArrayList<>();
			List<Member> memberList = page.getList();
			if (memberList.size() > 0){
				for (Member member1 : memberList) {
					MemberSubs memberSubs = new MemberSubs();
					memberSubs.setLoginName(member1.getLoginName());
					memberSubs.setSub(member1.getSub());
					memberSubs.setSubNum(member1.getSubNum());
					memberSubs.setTeamSumSub(member1.getTeamSumSub());
					memberSubs.setTeamSumSubPro(member1.getTeamSumSubPro());
					list.add(memberSubs);
				}
			}
			new ExportExcel("团队认购信息", MemberSubs.class).setDataList(list).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出团队认购信息记录失败！失败信息："+e.getMessage());
		}
		return j;
	}
	
}